<?php

namespace app\common\lib;

class MergePic
{
    // 打开图片
    public function open($input){
        $input = $_SERVER['DOCUMENT_ROOT'].$input;
        list($this->width, $this->height, $type) = getimagesize($input);
        $type = image_type_to_extension($type, false);
        $func = 'imagecreatefrom'.$type;
        $this->image = $func($input);
        return $this;
    }
    // 遮罩
    public function mask($alpha = 30){
        $img = imagecreate($this->width, $this->height);
        $img_color = imagecolorallocate($img, 0, 0, 0);
        imagefill($img, 0, 0, $img_color);
        imagecopymerge($this->image, $img, 0, 0, 0, 0, $this->width, $this->height, $alpha);
        imagedestroy($img);
        return $this;
    }
    // 模糊
    public function vague($num = 5){
        for($i=0; $i<$num; $i++){
            ImageFilter($this->image, IMG_FILTER_GAUSSIAN_BLUR, 0, 0, 0);
        }
        ImageFilter($this->image, IMG_FILTER_SMOOTH, 1);
        return $this;
    }
    // 添加文本
    public function text($text, $text2 = ''){
        $font = $_SERVER['DOCUMENT_ROOT'].'/font/siyuan.ttf';
        $text_color = imagecolorallocate($this->image, 255, 255, 255);
        $fontSize  = 36; 
        $dimensions = imagettfbbox($fontSize, 0, $font, $text);
        $center_width = ceil(($this->width - $dimensions[4]) / 2);
        imagettftext($this->image, $fontSize, 0, $center_width, $this->height/2, $text_color, $font, $text);

        if(!empty($text2)){
            $text_color2 = imagecolorallocate($image, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
            $fontSize2  = 24; 
            $dimensions2 = imagettfbbox($fontSize2, 0, $font, $text2);
            $center_width2 = ceil(($this->width - $dimensions2[4]) / 2);
            imagettftext($this->image, $fontSize2, 0, $center_width2, $this->height/2+$fontSize, $text_color, $font, $text2);
        }
        return $this;
    }
    //保存
    public function save(){
        $dirpath = '/uploads/merge/'.date('Ymd').'/';
        $filepath = $dirpath.mt_rand(1000,9999).time().'.png';
        $output = $_SERVER['DOCUMENT_ROOT'].$filepath;
        if (file_exists($_SERVER['DOCUMENT_ROOT'].$dirpath) == false){
            mkdir($_SERVER['DOCUMENT_ROOT'].$dirpath, 0700, true);
        }
        imagepng($this->image, $output, 9);
        imagedestroy($this->image);

        return $filepath;
    }

    public function __destruct(){
        imagedestroy($this->image);
    }
    
    
}